package com.zhisheng.day10_tlias.service.impl;

import com.zhisheng.day10_tlias.anno.MyBJ;
import com.zhisheng.day10_tlias.anno.MyOperateLogBJ;
import com.zhisheng.day10_tlias.entry.Dept;
import com.zhisheng.day10_tlias.mapper.DeptMapper;
import com.zhisheng.day10_tlias.service.DeptLogService;
import com.zhisheng.day10_tlias.service.DeptService;
import com.zhisheng.day10_tlias.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileNotFoundException;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
@Scope("prototype")
public class DeptServiceImpl implements DeptService {

//    @Autowired
    private DeptMapper deptMapper;

//    @Autowired
    private EmpService empService;



    @Autowired
    public DeptServiceImpl(DeptMapper deptMapper, EmpService empService, DeptLogService deptLogService) {
        this.deptMapper = deptMapper;
        this.empService = empService;
        this.deptLogService = deptLogService;
    }

    @Override
   // @MyBJ
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @MyOperateLogBJ
    public int delById(Integer id) throws FileNotFoundException {

        if(id == null){
            log.info("业务层拦截了删除的操作...因为参数为null....................................");
            return 0;
        }
        int deptCount = -1;
        int empCount = -1;
        try {
            // 删除员工表中的数据   xxx
             empCount = empService.delByDeptId(id);
           // FileInputStream fileInputStream = new FileInputStream("123.txt");
            deptCount = deptMapper.delById(id);
            //  业务层要追加一个新的业务,当执行这个方法的时候,无论是否删除成功,都要把删除的动作记录到日志表中
        } finally {
            // 调用记录日志的接口,传递一个日志对象
            if(deptCount == -1){
                deptLogService.insertDeptLog("删除:"+id+"号部门的时候,出异常了!");
            }else {
                deptLogService.insertDeptLog("删除:"+id+"号部门的结果影响有:"+deptCount+"行,删除该部门下的员工影响:"+empCount+"行!");
            }
        }


        return deptCount;
    }

    @Override
    @MyBJ
    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }

    @Override
    @MyOperateLogBJ
    public int updateById(Dept dept) {
        // 由于浏览器只传递了 id和name,因此需要设置对象的更新时间
        dept.setUpdateTime(LocalDateTime.now());
        return deptMapper.updateById(dept);
    }

    @Override
    @MyOperateLogBJ
    public int insert(Dept dept) {
        // 给对象补充两个数据
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        return deptMapper.insert(dept);
    }
    //    @Autowired
    private DeptLogService deptLogService;
}
